﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using AIStudio.Wpf.DiagramDesigner;
using AIStudio.Wpf.DiagramDesigner.Algorithms;
using AIStudio.Wpf.DiagramDesigner.Geometrys;
using AIStudio.Wpf.DiagramDesigner.Helpers;
using AIStudio.Wpf.Mind.Models;
using AIStudio.Wpf.Mind.ViewModels;

namespace AIStudio.Wpf.Mind.Helpers
{
    public class MindLayout : IMindLayout
    {
        public void Appearance(MindNode mindNode)
        {
            Appearance(mindNode, MindTheme.SkyBlue, false);
        }

        public void Appearance(MindNode mindNode, MindTheme mindTheme, bool initAppearance)
        {
            switch (mindNode.NodeLevel)
            {
                case 0:
                    {
                        if (initAppearance)
                        {
                            MindThemeHelper.ThemeChange(mindNode, mindTheme, initAppearance);

                            mindNode.ClearConnectors();
                            var port = new FullyCreatedConnectorInfo(mindNode.Root, mindNode, ConnectorOrientation.None, true) { XRatio = 0.5, YRatio = 0.5 };
                            mindNode.AddConnector(port);
                        }
                        mindNode.ShapeViewModel.SinkMarker.PathStyle = PathStyle.Circle;
                        mindNode.ShapeViewModel.SinkMarker.SizeStyle = SizeStyle.VerySmall;
                        mindNode.ConnectorOrientation = ConnectorOrientation.None;
                        break;
                    }
                case 1:
                    {
                        if (initAppearance)
                        {
                            MindThemeHelper.ThemeChange(mindNode, mindTheme, initAppearance);

                            mindNode.ClearConnectors();
                            var port1 = new FullyCreatedConnectorInfo(mindNode.Root, mindNode, ConnectorOrientation.Left, true) { XRatio = 0, YRatio = 0.5 };
                            mindNode.AddConnector(port1);
                            var port2 = new FullyCreatedConnectorInfo(mindNode.Root, mindNode, ConnectorOrientation.Right, true) { XRatio = 1, YRatio = 0.5 };
                            mindNode.AddConnector(port2);
                        }
                        mindNode.ShapeViewModel.SinkMarker.PathStyle = PathStyle.None;
                        mindNode.ShapeViewModel.SinkMarker.SizeStyle = SizeStyle.VerySmall;
                        mindNode.ConnectorOrientation = ConnectorOrientation.Left;
                        break;
                    }
                default:
                    {
                        if (initAppearance)
                        {
                            MindThemeHelper.ThemeChange(mindNode, mindTheme, initAppearance);

                            mindNode.ClearConnectors();
                            var port1 = new FullyCreatedConnectorInfo(mindNode.Root, mindNode, ConnectorOrientation.Left, true) { XRatio = 0, YRatio = 1 };
                            mindNode.AddConnector(port1);
                            var port2 = new FullyCreatedConnectorInfo(mindNode.Root, mindNode, ConnectorOrientation.Right, true) { XRatio = 1, YRatio = 1 };
                            mindNode.AddConnector(port2);

                            mindNode.CornerRadius = new System.Windows.CornerRadius(0);
                            mindNode.BorderThickness = new System.Windows.Thickness(0, 0, 0, 1);
                        }
                        mindNode.ShapeViewModel.SinkMarker.PathStyle = PathStyle.None;
                        mindNode.ShapeViewModel.SinkMarker.SizeStyle = SizeStyle.VerySmall;
                        mindNode.ConnectorOrientation = ConnectorOrientation.Left;
                        break;
                    }
            }
        }

        public ConnectionViewModel GetOrSetConnectionViewModel(MindNode source, MindNode sink, ConnectionViewModel connector = null)
        {
            if (source == null || sink == null)
                return null;

            if (connector == null)
            {
                connector = new ConnectionViewModel(source.Root, source.FirstConnector, sink.FirstConnector, DrawMode.ConnectingLineSmooth, RouterMode.RouterNormal);
            }
            else
            {
                connector?.UpdateConnectionMode(source.FirstConnector, sink.FirstConnector, DrawMode.ConnectingLineSmooth.ToString(), RouterMode.RouterNormal.ToString());
            }
            connector.EnabledForSelection = false;
            connector.IsHitTestVisible = false;
            connector.ColorViewModel.LineColor = source.ColorViewModel.LineColor;
            connector.ShapeViewModel.SinkMarker.PathStyle = source.ShapeViewModel.SinkMarker.PathStyle;
            connector.ShapeViewModel.SinkMarker.SizeStyle = source.ShapeViewModel.SinkMarker.SizeStyle;
            connector.SetPathGeneratorParameter(smoothMargin: 20, smoothAutoSlope: 0.2, orthogonalShapeMargin: 2, orthogonalGlobalBoundsMargin: 5);

            return connector;
        }

        public void UpdatedLayout(MindNode mindNode)
        {
            if (mindNode == null) return;

            mindNode.GetLevel0Node().LayoutUpdating = true;
            var size = MeasureOverride(mindNode);
            ArrangeOverride(mindNode);

            mindNode.Root.BringToFrontCommand.Execute(mindNode.Root.Items.OfType<DesignerItemViewModelBase>());

            mindNode.GetLevel0Node().LayoutUpdating = false;
        }

        public SizeBase MeasureOverride(MindNode mindNode, bool isExpanded = true)
        {
            var sizewithSpacing = mindNode.SizeWithSpacing;
            if (mindNode.Children?.Count > 0)
            {
                if (mindNode.NodeLevel == 0)
                {
                    var rights = mindNode.Children.Where((p, index) => index % 2 == 0).ToList();
                    rights.ForEach(p => p.ConnectorOrientation = ConnectorOrientation.Left);
                    var rightsizes = rights.Select(p => MeasureOverride(p, mindNode.IsExpanded && isExpanded)).ToArray();
                    var lefts = mindNode.Children.Where((p, index) => index % 2 == 1).ToList();
                    lefts.ForEach(p => p.ConnectorOrientation = ConnectorOrientation.Right);
                    var leftsizes = lefts.Select(p => MeasureOverride(p, mindNode.IsExpanded && isExpanded)).ToArray();
                    sizewithSpacing = new SizeBase(sizewithSpacing.Width + rightsizes.MaxOrDefault(p => p.Width) + +leftsizes.MaxOrDefault(p => p.Width), Math.Max(sizewithSpacing.Height, Math.Max(rightsizes.SumOrDefault(p => p.Height), leftsizes.SumOrDefault(p => p.Height))));
                }
                else
                {
                    var childrensizes = mindNode.Children.Select(p => MeasureOverride(p, mindNode.IsExpanded && isExpanded)).ToArray();
                    sizewithSpacing = new SizeBase(sizewithSpacing.Width + childrensizes.MaxOrDefault(p => p.Width), Math.Max(sizewithSpacing.Height, childrensizes.SumOrDefault(p => p.Height)));
                }
            }
            mindNode.DesiredSize = isExpanded ? sizewithSpacing : new SizeBase(0, 0);
            mindNode.Visible = isExpanded;

            return mindNode.DesiredSize;
        }

        public void ArrangeOverride(MindNode mindNode)
        {
            if (mindNode.NodeLevel == 0)
            {
                mindNode.DesiredPosition = mindNode.Position;

                if (mindNode.Children?.Count > 0)
                {
                    var rights = mindNode.Children.Where(p => p.ConnectorOrientation == ConnectorOrientation.Left).ToList();
                    double left = mindNode.DesiredPosition.X + mindNode.ItemWidth  + mindNode.Spacing.Width;
                    double lefttop = mindNode.DesiredPosition.Y + mindNode.ItemHeight / 2 - Math.Min(mindNode.DesiredSize.Height, rights.SumOrDefault(p => p.DesiredSize.Height)) / 2;
                    foreach (var child in rights)
                    {
                        child.Offset = new PointBase(child.Offset.X - child.RootNode.Offset.X, child.Offset.Y - child.RootNode.Offset.Y);
                        
                        child.DesiredPosition = new PointBase(left + child.Spacing.Width, lefttop + child.DesiredSize.Height / 2 - child.ItemHeight / 2);
                        child.Left = child.DesiredPosition.X + child.Offset.X;
                        child.Top = child.DesiredPosition.Y + child.Offset.Y;
                        lefttop += child.DesiredSize.Height;

                        ArrangeOverride(child);

                        var connector = mindNode.Root?.Items.OfType<ConnectionViewModel>().FirstOrDefault(p => p.SourceConnectorInfoFully?.DataItem == mindNode && p.SinkConnectorInfoFully?.DataItem == child);
                        connector?.SetSourcePort(mindNode.FirstConnector);
                        connector?.SetSinkPort(child.LeftConnector);
                        connector?.SetVisible(child.Visible);
                    }

                    var lefts = mindNode.Children.Where(p => p.ConnectorOrientation == ConnectorOrientation.Right).ToList();
                    double right = mindNode.DesiredPosition.X - mindNode.Spacing.Width;
                    double righttop = mindNode.DesiredPosition.Y + mindNode.ItemHeight / 2 - Math.Min(mindNode.DesiredSize.Height, lefts.SumOrDefault(p => p.DesiredSize.Height)) / 2;
                    foreach (var child in lefts)
                    {
                        child.Offset = new PointBase(child.Offset.X - child.RootNode.Offset.X, child.Offset.Y - child.RootNode.Offset.Y);
                        child.DesiredPosition = new PointBase(right - child.Spacing.Width - child.ItemWidth, righttop + child.DesiredSize.Height / 2 - child.ItemHeight / 2);
                        child.Left = child.DesiredPosition.X + child.Offset.X;
                        child.Top = child.DesiredPosition.Y + child.Offset.Y;
                        righttop += child.DesiredSize.Height;

                        ArrangeOverride(child);

                        var connector = mindNode.Root?.Items.OfType<ConnectionViewModel>().FirstOrDefault(p => p.SourceConnectorInfoFully?.DataItem == mindNode && p.SinkConnectorInfoFully?.DataItem == child);
                        connector?.SetSourcePort(mindNode.FirstConnector);
                        connector?.SetSinkPort(child.RightConnector);
                        connector?.SetVisible(child.Visible);
                    }
                }
                
                mindNode.Offset = new PointBase();//修正后归0
            }
            else
            {
                if (mindNode.GetLevel1Node().ConnectorOrientation == ConnectorOrientation.Left)
                {
                    double left = mindNode.DesiredPosition.X + mindNode.ItemWidth + mindNode.Spacing.Width;
                    double top = mindNode.DesiredPosition.Y + mindNode.ItemHeight / 2 - Math.Min(mindNode.DesiredSize.Height, mindNode.Children.SumOrDefault(p => p.DesiredSize.Height)) / 2;
                    if (mindNode.Children?.Count > 0)
                    {
                        foreach (var child in mindNode.Children)
                        {
                            child.Offset = new PointBase(child.Offset.X - child.RootNode.Offset.X, child.Offset.Y - child.RootNode.Offset.Y);
                            child.DesiredPosition = new PointBase(left + child.Spacing.Width, top + child.DesiredSize.Height / 2 - child.ItemHeight / 2);
                            child.Left = child.DesiredPosition.X + child.Offset.X;
                            child.Top = child.DesiredPosition.Y + child.Offset.Y;
                            top += child.DesiredSize.Height;

                            ArrangeOverride(child);

                            var connector = mindNode.Root?.Items.OfType<ConnectionViewModel>().FirstOrDefault(p => p.SourceConnectorInfoFully?.DataItem == mindNode && p.SinkConnectorInfoFully?.DataItem == child);
                            connector?.SetSourcePort(mindNode.RightConnector);
                            connector?.SetSinkPort(child.LeftConnector);
                            connector?.SetVisible(child.Visible);
                        }
                    }
                }
                else
                {
                    double right = mindNode.DesiredPosition.X  - mindNode.Spacing.Width;
                    double top = mindNode.DesiredPosition.Y + mindNode.ItemHeight / 2 - Math.Min(mindNode.DesiredSize.Height, mindNode.Children.SumOrDefault(p => p.DesiredSize.Height)) / 2;
                    if (mindNode.Children?.Count > 0)
                    {
                        foreach (var child in mindNode.Children)
                        {
                            child.Offset = new PointBase(child.Offset.X - child.RootNode.Offset.X, child.Offset.Y - child.RootNode.Offset.Y);
                            child.DesiredPosition = new PointBase(right - child.Spacing.Width - child.ItemWidth, top + child.DesiredSize.Height / 2 - child.ItemHeight / 2);
                            child.Left = child.DesiredPosition.X + child.Offset.X;
                            child.Top = child.DesiredPosition.Y + child.Offset.Y;
                            top += child.DesiredSize.Height;

                            ArrangeOverride(child);

                            var connector = mindNode.Root?.Items.OfType<ConnectionViewModel>().FirstOrDefault(p => p.SourceConnectorInfoFully?.DataItem == mindNode && p.SinkConnectorInfoFully?.DataItem == child);
                            connector?.SetSourcePort(mindNode.LeftConnector);
                            connector?.SetSinkPort(child.RightConnector);
                            connector?.SetVisible(child.Visible);
                        }
                    }
                }
            }


        }


    }
}
